// App.jsx
import React, { useState, useEffect } from 'react';
import Success from './images/success.png'
import ErrorPng from './images/error.png'
import FreePng from './images/free.png'
import DownloadPng from './images/download.png'
import RocketPng from './images/rocket.png'
import './App.css';
import {getMarketUrl} from "./utils";

function SuccessModal({ isOpen, onClose }) {
    if (!isOpen) return null;
    const urlParams = new URLSearchParams(window.location.search);
    const link = urlParams.get('link');

    return (
        <div className="modal-overlay">
            <div className="modal-content">
                <div className="modal-icon success">
                    <img src={Success} alt=""/>
                </div>
                <h2 className="modal-title">链接复制成功</h2>
                <p className="modal-description">文件较大，建议转发下载链接到电脑<br/>用电脑浏览器进行下载管理</p>
                <button className="modal-button confirm" onClick={onClose}>
                    确定
                </button>
                <button className="modal-button confirm" onClick={() => {
                    window.location.href = link
                }}>
                    手机浏览器打开
                </button>
            </div>
        </div>
    );
}

function InstallModal({isOpen, onClose, onInstall}) {
    if (!isOpen) return null;

    return (
        <div className="modal-overlay">
            <div className="modal-content">
                <div className="modal-icon error">
                    <img src={ErrorPng} alt=""/>
                </div>
                <h2 className="modal-title">未安装网盘</h2>
                <p className="modal-description">立刻跳转应用商店安装夸克</p>
                <div className="modal-buttons">
                    <button className="modal-button install" onClick={onInstall}>
                        确定
                    </button>
                </div>
            </div>
        </div>
    );
}

function App() {
    const [title, setTitle] = useState('');
    const [price, setPrice] = useState('');
    const [isSuccessModalOpen, setIsSuccessModalOpen] = useState(false);
    const [isInstallModalOpen, setIsInstallModalOpen] = useState(false);
    const [shareClickCount, setShareClickCount] = useState(0); // 新增状态记录点击次数

    useEffect(() => {
        // 从 URL 获取标题
        const urlParams = new URLSearchParams(window.location.search);
        const titleFromUrl = urlParams.get('title');
        if (titleFromUrl) {
            setTitle(titleFromUrl);
        }
        const priceFromUrl = urlParams.get('price');
        if (priceFromUrl) {
            setPrice(priceFromUrl);
        }
    }, []);

    // 复制文本到剪贴板
    const copyToClipboard = (text) => {
        // 现代浏览器方法
        if (navigator.clipboard && window.isSecureContext) {
            return navigator.clipboard.writeText(text)
                .then(() => true)
                .catch((err) => {
                    console.error('Failed to copy with clipboard API:', err);
                    return fallbackCopyToClipboard(text);
                });
        }
        // 降级方案
        return Promise.resolve(fallbackCopyToClipboard(text));
    };

    const fallbackCopyToClipboard = (text) => {
        try {
            // 创建临时文本区域
            const textArea = document.createElement('textarea');
            textArea.value = text;

            // 防止创建的元素可见
            textArea.style.position = 'fixed';
            textArea.style.top = '0';
            textArea.style.left = '0';
            textArea.style.width = '2em';
            textArea.style.height = '2em';
            textArea.style.padding = '0';
            textArea.style.border = 'none';
            textArea.style.outline = 'none';
            textArea.style.boxShadow = 'none';
            textArea.style.background = 'transparent';

            document.body.appendChild(textArea);

            // 选择文本
            textArea.focus();
            textArea.select();

            // iOS设备需要特殊处理
            const range = document.createRange();
            range.selectNodeContents(textArea);
            const selection = window.getSelection();
            selection.removeAllRanges();
            selection.addRange(range);
            textArea.setSelectionRange(0, textArea.value.length);

            // 执行复制
            const successful = document.execCommand('copy');

            // 清理
            document.body.removeChild(textArea);

            return successful;
        } catch (err) {
            console.error('Fallback copy failed:', err);
            return false;
        }
    };

    const handleShare = async () => {
        setShareClickCount(prevCount => prevCount + 1); // 增加点击次数

        // 如果是第二次点击，直接打开 quark.cn
        if (shareClickCount === 1) {
            window.location.href = 'https://www.quark.cn/';
            return;
        }

        // 第一次点击的原有逻辑
        const urlParams = new URLSearchParams(window.location.search);
        const shareCode = urlParams.get('share_code');
        const isQuarkInstalled = urlParams.get('quark') === '1';

        if (shareCode) {
            const copied = await copyToClipboard(shareCode);
            if (copied) {
                if (isQuarkInstalled) {
                    window.location.href = 'quark://';
                } else {
                    setIsInstallModalOpen(true);
                }
            } else {
                alert('分享码复制失败');
            }
        } else {
            alert('分享码不存在');
        }
    };

    const handleGetLink = async () => {
        const urlParams = new URLSearchParams(window.location.search);
        const link = urlParams.get('link');

        if (link) {
            const copied = await copyToClipboard(link);
            if (copied) {
                setIsSuccessModalOpen(true);
            }
        } else {
            alert('下载链接不存在');
        }
    };

    const handleInstall = () => {
        // 处理安装跳转逻辑
        window.location.href = getMarketUrl();
        setIsInstallModalOpen(false);
    };

    return (
        <div className="download-page">
            <h1 className="title">{title}</h1>

            <div className="body">
                <div className="download-card">
                    <div className="card-content">
                        <div className="icon free-icon">
                            <img src={FreePng} alt=""/>
                        </div>
                        <div className="text-content">
                            <h2>转存到网盘</h2>
                            <p>网盘会员完全免费，一键转存到自己的网盘</p>
                        </div>
                    </div>
                    <button className="download-button" onClick={handleShare}>
                        <span className="arrow"> <img src={DownloadPng} alt=""/></span> 一键转存
                    </button>
                </div>

                <div className="download-card">
                    <div className="card-content">
                        <div className="icon rocket-icon">
                            <img src={RocketPng} alt=""/>
                        </div>
                        <div className="text-content">
                            <h2>高速下载 {price ? `- ￥${price}元` : ''}</h2>

                            <p>极速下载，收费仅为下载流量成本，无需网盘会员和登录</p>
                        </div>
                    </div>
                    <button className="download-button" onClick={handleGetLink}>
                        <span className="arrow"> <img src={DownloadPng} alt=""/></span>
                        获取链接
                    </button>
                </div>

                <p className="footer-text">
                    所有资源来自网络公开资料的收集整理
                    <br/>
                    供所有家长免费使用
                </p>

                <SuccessModal
                    isOpen={isSuccessModalOpen}
                    onClose={() => setIsSuccessModalOpen(false)}
                />

                <InstallModal
                    isOpen={isInstallModalOpen}
                    onClose={() => setIsInstallModalOpen(false)}
                    onInstall={handleInstall}
                />
            </div>
        </div>
    );
}

export default App;
